<template>
  <div class="home-container">
    <!-- 头部 -->
    <div class="home-header">
      <div class="header-top">
        <div class="header-right">
          <van-icon name="more-o" size="20" @click="showUpgradeMessage" />
          <van-icon name="setting-o" size="20" @click="showUpgradeMessage" />
        </div>
      </div>
    </div>
    
    <!-- 轮播图 -->
    <van-swipe :autoplay="3000" indicator-color="#fff" class="banner">
      <van-swipe-item>
        <div class="banner-content">
          <div class="banner-text">
            <h3>健康生活</h3>
            <p>轻松简单</p>
          </div>
          <div class="banner-image">
            <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' fill='%234CD964'/%3E%3C/svg%3E" alt="医生" />
          </div>
        </div>
      </van-swipe-item>
    </van-swipe>
    
    <!-- 快捷功能 -->
    <div class="quick-actions">
      <van-grid :column-num="2" gutter="10">
        <van-grid-item @click="showUpgradeMessage">
          <div class="quick-action-item">
            <van-icon name="calendar-o" size="32" color="#007aff" />
            <span>门诊挂号</span>
            <p class="quick-action-desc">便捷预约挂号</p>
          </div>
        </van-grid-item>
        <van-grid-item @click="showUpgradeMessage">
          <div class="quick-action-item">
            <van-icon name="currency-cny" size="32" color="#007aff" />
            <span>门诊缴费</span>
            <p class="quick-action-desc">便捷预约挂号</p>
          </div>
        </van-grid-item>
        <van-grid-item>
          <div class="quick-action-item" @click.stop="goToQuestionnaire">
            <van-icon name="edit" size="32" color="#007aff" />
            <span>问卷调查</span>
            <p class="quick-action-desc">参与满意度调查</p>
          </div>
        </van-grid-item>
      </van-grid>
    </div>
    
    <!-- 公告 -->
    <div class="announcement" @click="showUpgradeMessage">
      <div class="announcement-left">
        <span class="announcement-tag">公告</span>
        <span class="announcement-text">智慧医院上线啦，手机也能问诊...</span>
      </div>
      <van-icon name="arrow-right" size="16" />
    </div>
    
    <!-- 功能分类 -->
    <div class="feature-tabs">
      <div class="tabs-header">
        <div :class="{ active: activeTab === 'outpatient' }" @click="activeTab = 'outpatient'">门诊</div>
        <div :class="{ active: activeTab === 'inpatient' }" @click="activeTab = 'inpatient'">住院</div>
        <div :class="{ active: activeTab === 'comprehensive' }" @click="activeTab = 'comprehensive'">综合</div>
        <div class="more" @click="showUpgradeMessage">更多</div>
      </div>
      
      <div class="feature-grid">
        <van-grid :column-num="4">
          <van-grid-item @click="showUpgradeMessage">
            <div class="feature-item">
              <div class="feature-icon">
                <van-icon name="document-text-o" size="24" />
              </div>
              <span>门诊报告</span>
            </div>
          </van-grid-item>
          <van-grid-item @click="showUpgradeMessage">
            <div class="feature-item">
              <div class="feature-icon">
                <van-icon name="time-o" size="24" />
              </div>
              <span>候诊查询</span>
            </div>
          </van-grid-item>
          <van-grid-item @click="showUpgradeMessage">
            <div class="feature-item">
              <div class="feature-icon">
                <van-icon name="edit-o" size="24" />
              </div>
              <span>自助开单</span>
            </div>
          </van-grid-item>
          <van-grid-item @click="showUpgradeMessage">
            <div class="feature-item">
              <div class="feature-icon">
                <van-icon name="clock-o" size="24" />
              </div>
              <span>医技预约</span>
            </div>
          </van-grid-item>
          <van-grid-item @click="showUpgradeMessage">
            <div class="feature-item">
              <div class="feature-icon">
                <van-icon name="replay-o" size="24" />
              </div>
              <span>我的复诊</span>
            </div>
          </van-grid-item>
          <van-grid-item @click="showUpgradeMessage">
            <div class="feature-item">
              <div class="feature-icon">
                <van-icon name="ticket-o" size="24" />
              </div>
              <span>自助取号</span>
            </div>
          </van-grid-item>
          <van-grid-item @click="showUpgradeMessage">
            <div class="feature-item">
              <div class="feature-icon">
                <van-icon name="nav-o" size="24" />
              </div>
              <span>门诊导诊单</span>
            </div>
          </van-grid-item>
          <van-grid-item @click="showUpgradeMessage">
            <div class="feature-item">
              <div class="feature-icon">
                <van-icon name="bill-o" size="24" />
              </div>
              <span>电子票据</span>
            </div>
          </van-grid-item>
        </van-grid>
      </div>
    </div>
    
    <!-- 健康资讯 -->
    <div class="health-info">
      <div class="section-title">健康资讯</div>
      <div class="info-item" @click="showUpgradeMessage">
        <div class="info-content">
          <h4>世界糖尿病日，应该注意什么</h4>
        </div>
        <van-icon name="arrow-right" size="16" />
      </div>
    </div>
    <!-- Coze -->
    <div id="coze-web-sdk-container" class="coze-container"></div>
    <!-- 智能客服（暂时不实现） -->
    <!-- <div class="customer-service" @click="showUpgradeMessage">
      <div class="service-icon">
        <van-icon name="chat-o" size="32" color="#fff" />
      </div>
      <span>智能客服</span>
    </div> -->
    
    <!-- 底部导航 -->
    <van-tabbar route v-model="active">
      <van-tabbar-item icon="home-o" to="/home">诊疗首页</van-tabbar-item>
      <van-tabbar-item icon="cloud-o" to="/website" @click="showUpgradeMessage">微官网</van-tabbar-item>
      <van-tabbar-item icon="chat-o" to="/messages" @click="showUpgradeMessage">消息中心</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { showDialog } from 'vant'
import { useRouter } from 'vue-router'

const router = useRouter()
const activeTab = ref<'outpatient' | 'inpatient' | 'comprehensive'>('outpatient')
const active = ref(0)

// 显示升级提示
const showUpgradeMessage = () => {
  showDialog({
    message: '该功能请联系管理员进行升级',
    confirmButtonText: '确定',
    showCancelButton: false
  })
}

// 跳转到问卷列表
const goToQuestionnaire = () => {
  try {
    router.push('/questionnaire').catch((err) => {
      // 如果是导航重复的错误，可以忽略
      if (err.name !== 'NavigationDuplicated') {
        console.error('路由跳转失败:', err)
      }
    })
  } catch (error) {
    console.error('路由跳转异常:', error)
  }
}

const goBack = () => {
  router.back()
}

let cozeClient: any = null

// 动态加载 Coze SDK 脚本
const loadCozeSDK = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (window.hasOwnProperty('CozeWebSDK')) {
      return resolve()
    }

    const script = document.createElement('script')
    script.src = 'https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/1.2.0-beta.19/libs/cn/index.js'
    script.async = true
    script.onload = () => resolve()
    script.onerror = reject
    document.head.appendChild(script)
  })
}

onMounted(async () => {
  try {
    await loadCozeSDK()

    // 确保只初始化一次
    if (cozeClient) return

    cozeClient = new (window as any).CozeWebSDK.WebChatClient({
      config: {
        bot_id: '7566218314562355238',
      },
      componentProps: {
        title: '智能客服',
        // 可选：自定义容器
        el: '#coze-web-sdk-container',
      },
      auth: {
        type: 'token',
        token: 'pat_kVnuO0L6OeQgTbRvvdnPybvjgC46xeF9iZyZaXAYQusORHhoGS5qAC8jlKzvKvkT',
        onRefreshToken: function () {
          // 实际项目中应调用后端接口刷新 token
          return 'pat_kVnuO0L6OeQgTbRvvdnPybvjgC46xeF9iZyZaXAYQusORHhoGS5qAC8jlKzvKvkT'
        }
      }
    })
  } catch (error) {
    console.error('Failed to load or initialize Coze SDK:', error)
  }
})

onUnmounted(() => {
  // 可选：销毁实例（SDK 是否支持 destroy 需查文档）
  if (cozeClient && typeof cozeClient.destroy === 'function') {
    cozeClient.destroy()
  }
  cozeClient = null
})
</script>

<style scoped>
.home-container {
  padding-bottom: 60px;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.home-header {
  padding: 15px;
  background-color: #fff;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  gap: 20px;
}

.banner {
  height: 120px;
  margin-bottom: 15px;
}

.banner-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  height: 100%;
  background-color: #4CD964;
}

.banner-text h3 {
  font-size: 24px;
  font-weight: bold;
  color: #fff;
  margin-bottom: 5px;
}

.banner-text p {
  font-size: 16px;
  color: #fff;
}

.banner-image img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}

.quick-actions {
  padding: 0 15px 15px;
}

.quick-action-item {
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  text-align: center;
}

.quick-action-item span {
  display: block;
  margin: 10px 0 5px;
  font-size: 16px;
  font-weight: bold;
}

.quick-action-desc {
  font-size: 12px;
  color: #666;
}

.announcement {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  background-color: #fff;
  margin-bottom: 15px;
}

.announcement-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.announcement-tag {
  padding: 2px 8px;
  background-color: #ff4444;
  color: #fff;
  font-size: 12px;
  border-radius: 4px;
}

.announcement-text {
  font-size: 14px;
  color: #333;
}

.feature-tabs {
  background-color: #fff;
  margin-bottom: 15px;
}

.tabs-header {
  display: flex;
  padding: 0 15px;
  border-bottom: 1px solid #f0f0f0;
}

.tabs-header > div {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.tabs-header > div.active {
  color: #007aff;
  border-bottom: 2px solid #007aff;
}

.tabs-header .more {
  flex: none;
}

.feature-grid {
  padding: 15px 0;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.feature-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.feature-item span {
  font-size: 12px;
  color: #666;
}

.health-info {
  background-color: #fff;
  padding: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}

.info-content h4 {
  font-size: 14px;
  color: #333;
}

.customer-service {
  position: fixed;
  right: 20px;
  bottom: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.service-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #007aff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 10px rgba(0, 122, 255, 0.3);
}

.customer-service span {
  font-size: 12px;
  color: #666;
}

.ai-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  background-color: white;
}

/* 如果启用返回头部 */
.back-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: white;
  height: 56px;
  position: relative;
  z-index: 10;
}

.back-icon {
  font-size: 24px;
  margin-right: 10px;
  cursor: pointer;
}

.back-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* Coze 容器 */
.coze-container {
  flex: 1;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
